# -*-* encoding:UTF-8 -*-
# author        : mengy
# date          : 2018/12/3
# description   : 图片转字符画（直接取文件）

from PIL import Image

width = 80
height = 60
img = Image.open("test.jpg")
out = "output2.txt"

ascii_char = list("$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\|()1{}[]?-_+~<>i!lI;:,\"^`'. ")


def img_to_char(r, g, b, alpha=256):
    if alpha == 0:
        return ' '
    length = len(ascii_char)
    gray = int(0.2126 * r + 0.7152 * g + 0.0722 * b)

    unit = (256.0 + 1) / length
    return ascii_char[int(gray / unit)]


if __name__ == '__main__':
    img = img.resize((width, height), Image.NEAREST)
    txt = ""

    for i in range(height):
        for j in range(width):
            txt += img_to_char(*img.getpixel((j, i)))
        txt += "\n"

    print(txt)

    open(out, "w").write(txt)
